const router = require('koa-router')()
const validator = require('../../utils/validator')
const ParamException = require('../../exceptions/paramException')
const registerRules = require('./controllers/register')
const jsonwebtoken = require('jsonwebtoken')
const { query } = require('../../db/mysql')
const secret = require('../../config/secret')
const { sign } = jsonwebtoken

// router.prefix('/log')

router.post('/login', async (ctx, next) => {
  try {
    // escape防止sql注入,经测试用''将要查询的值包括起来就能起到防止'--注释掉后后面的密码查询语句
    const name = ctx.request.body.name
    const password = ctx.request.body.password
    // const name = escape(ctx.request.body.name)
    // const password = escape(ctx.request.body.password)
    // console.log({
    //   name,
    //   password
    // })
    const sql = `select * from database_01.users where name='${name}' and password='${password}'`
    // console.log(sql)
    const res = await query(sql)
    // console.log(res)
    if (res.data?.length) {
      const token = jsonwebtoken.sign({ name }, secret, { expiresIn: '3h' })
      ctx.cookies.set(
        'token',
        token,
        {
          domain: 'localhost', // 设置 cookie 的域
          path: '/', // 设置 cookie 的路径
          maxAge: 72 * 60 * 60 * 1000, // cookie 的有效时间 ms
          expires: new Date('2021-12-30'), // cookie 的失效日期, 如果设置了 maxAge, expires 将没有作用
          httpOnly: true, // 是否要设置 httpOnly
          overwrite: true // 是否要覆盖已有的 cookie 设置
        }
      )
      ctx.body = {
        code: 200,
        data: {
          msg: '登录成功',
          token
        }
      }
    } else {
      ctx.body = {
        code: 400,
        msg: '账号或者密码有误'
      }
    }
  } catch (error) {
    ctx.body = error
  }
})

router.post('/logout', async (ctx, next) => {
  ctx.cookies.set('token', '', {
    maxAge: 0
  })
  ctx.body = {
    code: 200,
    data: {
      msg: '登出成功'
    }
  }
})

router.get('/auth', async (ctx, next) => {
  ctx.body = ctx.state.user // 该中间件将验证后的用户数据直接返回给浏览器
})

// 注册
router.post('/register', async (ctx, next) => {
  const { data, error } = await validator(ctx, registerRules)
  // console.log(data, error)
  // 如果validator返回error为true则不需要继续处理，这里validator已经将错误返回给客户端了。
  if (error) return
  const { name, score, password } = data
  const sql = `insert into database_01.users (name, score, password) values ('${name}', ${score}, '${password}')`
  const res = await query(sql)
  ctx.body = {
    code: res.code,
    msg: res.msg || '注册成功'
  }
})

// query获取get请求的传参
router.get('/test', async (ctx, next) => {
  ctx.status = 200
  ctx.body = {
    query: ctx.query
  }
})

module.exports = router
